<?php


namespace app\model;


use think\facade\Cache;
use think\facade\Db;
use utils\Define;

class Activity
{

    /**
     * 签到
     * @param $data
     * @return \think\Response
     */
    public function Sign($data)
    {
        RedisLock('Sign_' . $data->user_id);
        Db::startTrans();
        try {
            $where[] = ['user_id', '=', $data->user_id];
            $where[] = ['type', '=', 3];
            $is_sign = Db::name('money_log')->where($where)->whereTime('created_time', 'between', [(DateTime()['t_s']), (DateTime()['t_e'])])->count();
            if ($is_sign > 0) {
                return app('json')->json_error('今天已签到');
            }
            //查看本月累计签到天数
            $sign_day = $this->signMsg(['user_id' => $data->user_id], 2) + 1;
            switch ($sign_day) {
                case 14:
                    $integral = Define::SignSpecifyDayValue;
                    break;
                case 21:
                    $integral = Define::SignSpecifyDayValue;;
                    break;
                case 30:
                    $integral = Define::SignSpecifyDayValue;;
                    break;
                default:
                    $integral = SystemConfig('day_integral');
            }
            MoneyLog::SetUserMoney($data->user_id, $data->user->integral, $integral, 3);
            $data->user->integral += $integral;
            if ($data->user->save()) {
                Db::commit();
                return app('json')->json_success('成功');
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return app('json')->json_error('签到失败' . $exception->getMessage());

        }

    }


    /**
     * 签到信息
     * @param $data
     * @param int $type
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function signMsg($data, $type = 1)
    {
        $date = date("Y-m-d");
        $first = date('Y-m-01', strtotime($date));
        $last = date('Y-m-d', strtotime("$first +1 month -1 day"));
        $result = Db::name('money_log')
            ->field("DATE_FORMAT(created_time,'%Y-%m-%d') as created_time,money")
            ->where(['type' => 3, 'user_id' => $data['user_id']])
            ->whereTime('created_time', 'between', [$first . ' 00:00:00', $last . ' 23:59:59'])
            ->order('id desc')
            ->select()
            ->toArray();
        $arr = [];
        $result1 = array_column($result, 'created_time');
        $result2 = $this->get_month($first, $last);
        $i = 0;
        $sign_day = 0;
        foreach ($result2 as $v) {
            ++$i;
            $arr[$v]['month_day'] = $v;
            if (in_array($v, $result1)) {
                $sign_day += 1;
                $arr[$v]['is_sign'] = 1;
            } else {
                $vs = date('Ymd', strtotime($v));
                $d = date("Ymd");
                if ($vs < $d) {
                    $sign_day = 0;
                }
                $arr[$v]['is_sign'] = 0;
            }
            $arr[$v]['integral'] = SystemConfig('day_integral');
            switch ($i) {
                case 14:
                    $arr[$v]['integral'] = Define::SignSpecifyDayValue;
                    break;
                case 21:
                    $arr[$v]['integral'] = Define::SignSpecifyDayValue;
                    break;
                case 30:
                    $arr[$v]['integral'] = Define::SignSpecifyDayValue;
                    break;
            }
        }
        $arr = array_values($arr);
        if ($type == 2) {
            return $sign_day;
        }
        return app('json')->json_success('成功', ['list' => $arr, 'sign_day' => $sign_day, 'integral' => 200]);
    }


    /**
     * 获取本月天数
     * @param $start
     * @param $end
     * @return array
     */
    function get_month($start, $end)
    {
        $days = date("t");
        for ($i = 0; $i < intval($days); $i++) {
            $day[] = date('Y-m-d', strtotime("+" . $i . " day", strtotime(date("Y-m-01"))));
        }
        return $day;
    }


    /**
     * 视频回调接口
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function video($user_id)
    {
        RedisLock('Video_task_' . $user_id);
        $user = User::find($user_id);
        if (!$user) {
            return app('json')->json_error('user not found !');
        }
        //查看用户今日看视频的次数
        $redis = Cache::store('redis');
        $key = 'video_task_' . $user_id . '_' . date('Y-m-d', time());
        $today_count = $redis->get($key);
        if ($today_count) {
            $redis->incr($key);
            $today_count += 1;
        } else {
            $time = strtotime(date('Y-m-d', strtotime('+1 day'))) - 3;
            $redis->set($key, 1, $time - time());
            $today_count = 1;
        }
        //查看用户是否领取任务奖励
        if ($today_count <= 10) {
            Db::startTrans();
            try {
                MoneyLog::SetUserMoney($user_id, $user->integral, SystemConfig('video_integral'), 5);
                //没有领取过新手奖励
                if ($today_count >= Define::VideoTaskNum && $user->is_video === 0) {
                    $user->is_video = 1;
                    $user->is_active = 1;
                    $user->save();
                    //发放新手奖励
                    $this->NewbieRewards($user->id);
                }
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                return app('json')->json_success('失败');
            }

        }
        return app('json')->json_success('成功');
    }


    /**
     * 发放新手奖励
     */
    public function NewbieRewards($user_id)
    {
        $user = User::find($user_id);
        if (!$user) {
            return false;
        }
        if ($user->is_newbie_tutorial == 1 && $user->is_video == 1 && $user->is_real_name == 1) {
            MoneyLog::SetUserMoney($user_id, $user->integral, SystemConfig('novice_task_bonus_points'), 10);
        }
    }

}